<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    body {
        height: 1500px;
    }

    div.topBar {
        width: 100%;
        height: 50px;
        background: skyblue;
        font: 35px/50px "";
        color: white;
        text-align: center;
        display: none;
    }

    div.goTop {
        width: 50px;
        height: 50px;
        background-color: hotpink;
        font: 20px/25px "";
        color: white;
        text-align: center;
        position: fixed;
        right: 25px;
        bottom: 25px;
        /* display: none; */
        opacity: 0;
        transition: .5s linear;
    }

    div.goTop.active {
        /* display: block; */
        opacity: 1;
        cursor: pointer;
    }
</style>

<body>
    <div class="topBar">顶部栏</div>
    <div class="goTop">回到顶部</div>
</body>
<script>
    //1.先获取元素
    var goTop = document.querySelector(".goTop")
    var topBar = document.querySelector(".topBar")
    //2.给浏览器设置滚动事件,当浏览器滚动,执行一系列操作
    window.onscroll = function () {
        var scrollTop = document.documentElement.scrollTop//获取当前document距离顶部的距离
        if (scrollTop >= 300) {//当浏览器滚动超过300px时
            //让goTop出现,即:给goTop添加active类名
            goTop.classList.add("active")
        } else {
            goTop.classList.remove("active")
        }
    }
    //3.给goTop设置点击事件
    goTop.onclick = function () {
        window.scrollTo({
            top:0,
            behavior:"smooth"
        })
    }
</script>

</html>